package com.oromwin.repos.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposConfig;
import com.oromwin.repos.server.thread.SocketThread;

public class ReposSocketServer extends Thread {
    private Log log = Logger.getLog(ReposSocketServer.class);
    private ServerSocket server = null;

    public ReposSocketServer(String filepath) throws IOException {
        server = new ServerSocket(ReposConfig.getInstance().getReposSocketPort());
        if (filepath != null) {
            ReposConfig.getInstance().loadProperties(filepath);
        }
    }

    public void run() {
        while (true) {
            // TODO: 초기에 데이터베이스에서 정보와 환경변수에서 설정된 정보 및 로컬 디스크 정보와 일치하는 지를 검증한다.
            try {
                if (log.isInfoEnabled()) log.info("SocketServer waiting for connection");
                Socket socket = server.accept();
                SocketThread thead = new SocketThread(socket); // need to pass client input/output socket stream also
                thead.start();
                
            } catch (IOException e) {
                System.err.println("Oh, dear me! " + e);
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] argv) throws IOException {
        String configPath = null;
        if (argv.length == 1) {
            configPath = argv[0];
        }
        new ReposSocketServer(configPath).start();
    }
    
}
